package com.yc.myPredicateFactory;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import java.time.LocalTime;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

/**
 * 谓词工厂类：工厂方法模式生产谓词
 * @author zwei
 * @create 2024-09-09 20:28
 */
@Slf4j
@Component
public class ServiceTimeBetweenRoutePredicateFactory extends AbstractRoutePredicateFactory<ServiceTimeBetweenRoutePredicateFactory.CustomTimeBetweenConfig> {

    public ServiceTimeBetweenRoutePredicateFactory() {
        super(CustomTimeBetweenConfig.class);
    }

    //业务逻辑判断
    @Override
    public Predicate<ServerWebExchange> apply(CustomTimeBetweenConfig config) {
        LocalTime startTime = config.getStartTime();
        LocalTime endTime = config.getEndTime();
        //创建谓词对象
//        return new Predicate<ServerWebExchange>() {
//            @Override
//            public boolean test(ServerWebExchange serverWebExchange) {
//                LocalTime now = LocalTime.now();
//                return now.isAfter(startTime) && now.isBefore(endTime); //判断当前时间是否在指定区间内
//            }
//        };
        //使用lambda表达式       serverWebExchange请求对象 相当于request
        return serverWebExchange -> {
            LocalTime now = LocalTime.now();
            return now.isAfter(startTime) && now.isBefore(endTime); //判断当前时间是否在指定区间内
        };
    }
    //用于接收yml中的配置CustTimeBetween=上午6点到下午6点
    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("startTime", "endTime");
    }

    //配置类
    @Data
    public static class CustomTimeBetweenConfig {
        private LocalTime startTime;
        private LocalTime endTime;
    }
}
